package com.example.tomatotodo;

import static com.example.tomatotodo.util.TokenManager.isLoggedIn;

import android.app.AlertDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.content.Context;
import android.widget.Toast;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Toast;
import androidx.annotation.Nullable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.example.tomatotodo.api.ApiClient;
import com.example.tomatotodo.api.ApiService;
import com.example.tomatotodo.model.Result;
import com.example.tomatotodo.model.TodoSettingDTO;
import com.example.tomatotodo.util.CloudSyncManager;
import com.example.tomatotodo.util.TokenManager;
import com.google.android.material.imageview.ShapeableImageView;
import com.google.gson.Gson;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ProfileFragment extends Fragment {
    private static final String TAG = "ProfileFragment";
    // 测试用token
    private static final String token = "Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIyIiwiaWF0IjoxNzU1MTczMzEwLCJleHAiOjE3NTUyNTk3MTB9.ZuLhsvS26zCVsTKOthC-0aP6qO5B4dKhFRkscaKLzUk";
    private static final int REQUEST_CODE_PICK_IMAGE = 1001; // 图片选择请求码
    private static final String TAG_AVATAR = "AvatarUpload"; // 头像上传日志标签

    private ShapeableImageView avatarImageView;
    private TextView userNameTextView;
    private Button btnSync;
    private Button btnSettings;
    private Button btnLogout;

    private CloudSyncManager cloudSyncManager;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_profile, container, false);

        // 初始化云同步管理器
        cloudSyncManager = new CloudSyncManager(requireContext());

        // 获取 setting_header include 的控件
        View navHeader = view.findViewById(R.id.include_setting_header);
        if (navHeader != null) {
            ShapeableImageView userImage = navHeader.findViewById(R.id.user_image);
            TextView nickName = navHeader.findViewById(R.id.nick_name);
            TextView userAutograph = navHeader.findViewById(R.id.user_autograph);
            // 初始化为默认空头像（未登录状态）
            userImage.setImageResource(R.drawable.default_photo); // 强制默认空头像
            // 示例数据
            nickName.setText("未登录");
            userAutograph.setText("未登录");
            // 检查登录状态并更新UI
            updateUserInfo(nickName, userAutograph, userImage); // 新增：传入头像ImageView
            // 可以设置头像 userImage.setImageResource(...) 或加载网络图片
            userImage.setOnClickListener(v -> {
                // 跳转到登录页面
                android.content.Intent intent = new android.content.Intent(getActivity(), LoginActivity.class);
                startActivity(intent);
            });
        }

        // 获取 other_body include 的控件
        View otherBody = view.findViewById(R.id.include_other_body);
        if (otherBody != null) {
            // 获取 ScrollView 内部的根 LinearLayout
            ScrollView scrollView = (ScrollView) otherBody;
            View scrollChild = scrollView.getChildAt(0);
            if (scrollChild instanceof LinearLayout) {
                LinearLayout rootLinearLayout = (LinearLayout) scrollChild;

                // 获取包含所有功能项的 LinearLayout (RelativeLayout 容器)
                if (rootLinearLayout.getChildCount() > 0) {
                    View itemsContainer = rootLinearLayout.getChildAt(0);
                    if (itemsContainer instanceof LinearLayout) {
                        LinearLayout itemsLinearLayout = (LinearLayout) itemsContainer;

                        // 遍历所有 RelativeLayout 功能项并设置点击监听
                        for (int i = 0; i < itemsLinearLayout.getChildCount(); i++) {
                            View item = itemsLinearLayout.getChildAt(i);
                            if (item instanceof RelativeLayout) {
                                item.setOnClickListener(v -> {
                                    if (!isLoggedIn(getActivity())) {
                                        Toast.makeText(getActivity(), "当前未登录状态", Toast.LENGTH_SHORT).show();
                                    }
                                });
                            }
                        }
                    }
                }
            }

            // 获取所有功能项视图（原有代码保留）
            View btn1 = otherBody.findViewById(R.id.btn_1);
            TextView statisticData = otherBody.findViewById(R.id.statistic_data);
            View btn2 = otherBody.findViewById(R.id.btn_2);
            TextView backup = otherBody.findViewById(R.id.backup);
            View btn3 = otherBody.findViewById(R.id.btn_3);
            TextView tv3 = otherBody.findViewById(R.id.tV_3);
            View btn4 = otherBody.findViewById(R.id.btn_4);
            TextView otherSetting = otherBody.findViewById(R.id.other_setting);
            View btn5 = otherBody.findViewById(R.id.btn_5);
            TextView tv5 = otherBody.findViewById(R.id.tV_5);
            Button btnQuit = otherBody.findViewById(R.id.btn_quit);

            // 创建通用的未登录检查点击监听器
            View.OnClickListener checkLoginListener = v -> {
                // 修复: 直接读取 SharedPreferences 判断登录状态，与 updateUserInfo 逻辑统一
                SharedPreferences prefs = getActivity().getSharedPreferences("user_info", Context.MODE_PRIVATE);
                String username = prefs.getString("username", null);
                boolean isLogged = username != null && !username.isEmpty();

                Log.d(TAG, "检查登录状态: " + isLogged); // 输出实际登录状态
                if (!isLogged) {
                    Toast.makeText(getActivity(), "当前未登录状态", Toast.LENGTH_SHORT).show(); // 使用getActivity()确保上下文正确
                } else {
                    // 已登录状态下，判断是否点击"修改用户信息"相关视图
                    if (v.getId() == R.id.btn_1 || v.getId() == R.id.statistic_data) {
                        // 跳转到用户更新页面（activity_update.xml对应的Activity）
                        Intent intent = new Intent(getActivity(), UpdateActivity.class);
                        startActivity(intent);
                    }
                    // 新增：上传头像（点击btn_3或tV_3时触发）
                    else if (v.getId() == R.id.btn_3 || v.getId() == R.id.tV_3) {
                        Log.d(TAG_AVATAR, "触发头像上传：打开本地图库");
                        openImagePicker(); // 打开图库选择图片
                    }
                    // 云同步与恢复功能（点击btn_2或backup时触发）
                    else if (v.getId() == R.id.btn_2 || v.getId() == R.id.backup) {
                        Log.d(TAG, "触发云同步与恢复功能");
                        cloudSyncManager.showSyncDialog();
                    }
                }
                // 其他功能项可在此处扩展逻辑
            };

            // 为所有功能项设置点击事件
            btn1.setOnClickListener(checkLoginListener);
            statisticData.setOnClickListener(checkLoginListener);
            btn2.setOnClickListener(checkLoginListener);
            backup.setOnClickListener(checkLoginListener);
            btn3.setOnClickListener(checkLoginListener);
            tv3.setOnClickListener(checkLoginListener);
            btn4.setOnClickListener(checkLoginListener);
            otherSetting.setOnClickListener(checkLoginListener);
            btn5.setOnClickListener(checkLoginListener);
            tv5.setOnClickListener(checkLoginListener);

            // 退出登录按钮点击事件
            btnQuit.setOnClickListener(v -> {
                SharedPreferences prefs = getActivity().getSharedPreferences("user_info", Context.MODE_PRIVATE);
                String username = prefs.getString("username", null);
                boolean isLogged = username != null && !username.isEmpty();

                if (isLogged) {
                    // 执行退出登录逻辑 (清除用户信息)
                    prefs.edit().clear().apply();

                    // 更新UI显示为未登录状态（强制默认空头像）
                    if (navHeader != null) {
                        TextView nickName = navHeader.findViewById(R.id.nick_name);
                        TextView userAutograph = navHeader.findViewById(R.id.user_autograph);
                        ShapeableImageView userImage = navHeader.findViewById(R.id.user_image);
                        nickName.setText("未登录");
                        userAutograph.setText("未登录");
                        userImage.setImageResource(R.drawable.default_photo); // 强制重置为默认空头像
                    }

                    Toast.makeText(getActivity(), "退出登录成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getActivity(), "当前未登录状态", Toast.LENGTH_SHORT).show();
                }
            });
        }

        return view;
    }
    // 新增：当Fragment恢复可见时刷新用户信息（例如从UpdateActivity返回）
    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG, "ProfileFragment 恢复可见，刷新用户信息");

        View view = getView();
        if (view != null) {
            // 重新获取导航头布局
            View navHeader = view.findViewById(R.id.include_setting_header);
            if (navHeader != null) {
                // 重新获取用户名和头像控件
                TextView nickName = navHeader.findViewById(R.id.nick_name);
                TextView userAutograph = navHeader.findViewById(R.id.user_autograph);
                ShapeableImageView userImage = navHeader.findViewById(R.id.user_image);

                // 调用updateUserInfo刷新最新数据（会从SharedPreferences读取更新后的用户名）
                updateUserInfo(nickName, userAutograph, userImage);
            }
        }
    }

    // 新增：更新用户信息显示
// 修改: 扩展updateUserInfo方法，增加头像显示逻辑
    private void updateUserInfo(TextView nickName, TextView userAutograph, ShapeableImageView avatarImageView) {
        if (getActivity() == null) return;

        SharedPreferences prefs = getActivity().getSharedPreferences("user_info", Context.MODE_PRIVATE);
        String username = prefs.getString("username", null);
        String avatarPath = prefs.getString("avatar_path", null); // 读取头像路径

        if (username != null && !username.isEmpty()) {
            // 已登录：更新用户名和头像
            nickName.setText(username);
            userAutograph.setText("已登录");

            // 加载并显示头像
            if (avatarPath != null && avatarImageView != null) {
                loadAvatarFromLocal(avatarPath, avatarImageView);
            } else {
                // 新增：头像路径为空（无头像），显示默认头像
                avatarImageView.setImageResource(R.drawable.default_photo);
            }
        } else {
            // 未登录：强制显示默认空头像和未登录状态
            nickName.setText("未登录");
            userAutograph.setText("未登录");
            avatarImageView.setImageResource(R.drawable.default_photo); // 强制使用默认空头像
        }
    }
    // 新增: 从本地加载头像并显示
    private void loadAvatarFromLocal(String avatarPath, ShapeableImageView imageView) {
        File avatarFile = new File(avatarPath);
        if (avatarFile.exists()) {
            // 加载本地图片到ImageView
            Bitmap bitmap = BitmapFactory.decodeFile(avatarPath);
            if (bitmap != null) {
                imageView.setImageBitmap(bitmap);
                Log.d(TAG, "头像加载成功: " + avatarPath);
            } else {
                Log.e(TAG, "头像解码失败: " + avatarPath);
                imageView.setImageResource(R.drawable.default_photo); // 解码失败显示默认图
            }
        } else {
            Log.e(TAG, "头像文件不存在: " + avatarPath);
            imageView.setImageResource(R.drawable.default_photo); // 文件不存在显示默认图
        }
    }
    /**
     * 打开本地图库选择图片
     */
    private void openImagePicker() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("image/*"); // 仅允许选择图片
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);
    }
    /**
     * 处理图库返回的图片结果
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_PICK_IMAGE && resultCode == Activity.RESULT_OK && data != null) {
            Uri imageUri = data.getData();
            if (imageUri != null) {
                Log.d(TAG_AVATAR, "选中图片URI: " + imageUri.toString());

                // 将URI转换为文件并上传
                uploadAvatarImage(imageUri);
            } else {
                Log.e(TAG_AVATAR, "选中图片URI为空");
                Toast.makeText(getActivity(), "选择图片失败", Toast.LENGTH_SHORT).show();
            }
        }
    }
    /**
     * 将选中的图片上传到服务器
     */
    private void uploadAvatarImage(Uri imageUri) {
        if (getActivity() == null) return;

        try {
            // 从URI获取文件路径（适配不同Android版本）
            InputStream inputStream = getActivity().getContentResolver().openInputStream(imageUri);
            File tempFile = File.createTempFile("avatar", ".jpg", getActivity().getCacheDir());
            FileOutputStream outputStream = new FileOutputStream(tempFile);
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            inputStream.close();
            outputStream.close();

            Log.d(TAG_AVATAR, "临时文件创建成功: " + tempFile.getAbsolutePath());

            // 创建请求体
            RequestBody requestFile = RequestBody.create(MediaType.parse("image/jpeg"), tempFile);
            MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", tempFile.getName(), requestFile);

            // 获取Token
            String token = TokenManager.getToken(getActivity());
            if (token == null) {
                Log.e(TAG_AVATAR, "上传失败：Token为空");
                Toast.makeText(getActivity(), "上传失败，请重新登录", Toast.LENGTH_SHORT).show();
                return;
            }

            // 调用上传接口
            ApiService apiService = ApiClient.getClient().create(ApiService.class);
            Call<Result<String>> call = apiService.uploadAvatar("Bearer " + token, filePart);
            Log.d(TAG_AVATAR, "开始上传头像...");

            call.enqueue(new Callback<Result<String>>() {
                @Override
                public void onResponse(Call<Result<String>> call, Response<Result<String>> response) {
                    if (response.isSuccessful() && response.body() != null) {
                        Result<String> result = response.body();
                        if (result.getCode() == 200 && result.getData() != null) {
                            Log.d(TAG_AVATAR, "上传成功，头像路径: " + result.getData());
                            Toast.makeText(getActivity(), "头像上传成功", Toast.LENGTH_SHORT).show();
                            // 新增：上传成功后获取并刷新新头像
                            SharedPreferences prefs = getActivity().getSharedPreferences("user_info", Context.MODE_PRIVATE);
                            long userId = prefs.getLong("user_id", -1); // 获取用户ID
                            if (userId != -1) {
                                fetchNewAvatar(userId); // 调用获取新头像方法
                            } else {
                                Log.e(TAG_AVATAR, "用户ID不存在，无法刷新头像");
                            }
                        } else {
                            Log.e(TAG_AVATAR, "上传失败：" + result.getMessage());
                            Toast.makeText(getActivity(), "上传失败: " + result.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Log.e(TAG_AVATAR, "上传失败，响应码: " + response.code());
                        Toast.makeText(getActivity(), "上传失败，服务器错误", Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void onFailure(Call<Result<String>> call, Throwable t) {
                    Log.e(TAG_AVATAR, "上传网络错误: " + t.getMessage(), t);
                    Toast.makeText(getActivity(), "上传失败，请检查网络", Toast.LENGTH_SHORT).show();
                }
            });

        } catch (IOException e) {
            Log.e(TAG_AVATAR, "文件处理失败: " + e.getMessage(), e);
            Toast.makeText(getActivity(), "图片处理失败", Toast.LENGTH_SHORT).show();
        }
    }
    // 新增：获取新头像并刷新UI
    private void fetchNewAvatar(long userId) {
        String token = TokenManager.getToken(getActivity());
        if (token == null) {
            Log.e(TAG_AVATAR, "获取新头像失败：Token为空");
            return;
        }

        ApiService apiService = ApiClient.getClient().create(ApiService.class);
        Call<ResponseBody> call = apiService.getAvatar("Bearer " + token, userId);

        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                if (response.isSuccessful() && response.body() != null) {
                    try {
                        byte[] newAvatarBytes = response.body().bytes();
                        if (newAvatarBytes.length == 0) {
                            Log.e(TAG_AVATAR, "新头像数据为空，清除本地头像路径");
                            // 清除头像路径，触发默认头像显示
                            SharedPreferences prefs = getActivity().getSharedPreferences("user_info", Context.MODE_PRIVATE);
                            prefs.edit().remove("avatar_path").apply();

                            // 立即刷新UI为默认头像
                            View navHeader = getView().findViewById(R.id.include_setting_header);
                            if (navHeader != null) {
                                ShapeableImageView userImage = navHeader.findViewById(R.id.user_image);
                                userImage.setImageResource(R.drawable.default_photo);
                            }
                            return;
                        }

                        // 覆盖保存新头像到本地（与原路径一致）
                        File avatarFile = new File(getActivity().getFilesDir(), "avatar_" + userId + ".jpg");
                        try (FileOutputStream fos = new FileOutputStream(avatarFile)) {
                            fos.write(newAvatarBytes);
                            Log.d(TAG_AVATAR, "新头像保存成功: " + avatarFile.getAbsolutePath());

                            // 更新SharedPreferences中的头像路径（确保路径正确）
                            SharedPreferences prefs = getActivity().getSharedPreferences("user_info", Context.MODE_PRIVATE);
                            prefs.edit().putString("avatar_path", avatarFile.getAbsolutePath()).apply();

                            // 刷新UI显示新头像
                            View navHeader = getView().findViewById(R.id.include_setting_header);
                            if (navHeader != null) {
                                ShapeableImageView userImage = navHeader.findViewById(R.id.user_image);
                                loadAvatarFromLocal(avatarFile.getAbsolutePath(), userImage); // 重新加载本地头像
                            }
                        } catch (IOException e) {
                            Log.e(TAG_AVATAR, "新头像保存失败: " + e.getMessage(), e);
                        }
                    } catch (IOException e) {
                        Log.e(TAG_AVATAR, "读取新头像数据失败: " + e.getMessage(), e);
                    }
                } else {
                    Log.e(TAG_AVATAR, "获取新头像失败，响应码: " + response.code());
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                Log.e(TAG_AVATAR, "获取新头像网络错误: " + t.getMessage(), t);
            }
        });
    }

    // ProfileFragment.java 中的 syncTodoSettings 方法
    private void syncTodoSettings() {
        ApiService apiService = ApiClient.getClient().create(ApiService.class);
        Call<Result<List<TodoSettingDTO>>> call = apiService.pullTodoSettings(token);

        call.enqueue(new Callback<Result<List<TodoSettingDTO>>>() {
            @Override
            public void onResponse(Call<Result<List<TodoSettingDTO>>> call, Response<Result<List<TodoSettingDTO>>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    Result<List<TodoSettingDTO>> result = response.body();

                    if (result.getCode() == 200 && result.getData() != null) {
                        List<TodoSettingDTO> todoSettings = result.getData();

                        // 将结果转换为JSON字符串
                        Gson gson = new Gson();
                        String json = gson.toJson(todoSettings);

                        // 输出到日志
                        Log.d(TAG, "Sync successful: " + json);

                        // 显示弹窗
                        showResultDialog(json);
                    } else {
                        Log.e(TAG, "Sync failed with code: " + result.getCode() + ", message: " + result.getMessage());
                        showResultDialog("同步失败，错误码: " + result.getCode() + ", 信息: " + result.getMessage());
                    }
                } else {
                    Log.e(TAG, "Sync failed with code: " + response.code());
                    showResultDialog("同步失败，错误码: " + response.code());
                }
            }

            @Override
            public void onFailure(Call<Result<List<TodoSettingDTO>>> call, Throwable t) {
                Log.e(TAG, "Sync failed with error: " + t.getMessage());
                showResultDialog("同步失败: " + t.getMessage());
            }
        });
    }


    private void showResultDialog(String message) {
        AlertDialog.Builder builder = new AlertDialog.Builder(requireContext());
        builder.setTitle("同步结果")
                .setMessage(message)
                .setPositiveButton("确定", (dialog, which) -> dialog.dismiss())
                .show();
    }
}
